import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/widgets/base/number_layout.dart';
import 'package:flutter_rider/main/widgets/base/pop_pick_spu.dart';
import 'package:flutter_rider/main/widgets/base/task_layout.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/pop/pop_shops_list.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/main/page/address_page.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/utils/upload_image_helper.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/event/click_address_event.dart';
import 'package:flutter_rider/event/click_shop_event.dart';
import 'package:flutter_rider/event/click_amount_event.dart';
import 'package:flutter_rider/utils/alib.dart';
import 'confirm_order_success.dart';

class CopyOrderPage extends StatefulWidget {
  dynamic data;
  CopyOrderPage(this.data, {Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return CopyOrderPageState();
  }
}

class CopyOrderPageState extends State<CopyOrderPage> {
  final NumberLayoutController _weightLayoutController = NumberLayoutController(0);
  final NumberLayoutController _qtyLayoutController = NumberLayoutController(0);
  final TaskLayoutController _taskLayoutController = TaskLayoutController(0);
  final _fhNameTextController = TextEditingController();
  final _fhPhoneTextController = TextEditingController();
  final _fhCarNoTextController = TextEditingController();
  final _shNameTextController = TextEditingController();
  final _shPhoneTextController = TextEditingController();
  final _shCarNoTextController = TextEditingController();
  late StreamSubscription _eventFn;
  late StreamSubscription _eventFn1;
  dynamic _data;
  /// 货物类别下标
  var _categoryIndex = 0;
  /// spu的每项的下标
  var _spuKeyIndex = 0;
  /// spu的每项子项的下标
  var _spuValIndex = 0;
  var _unit = 0;
  var _unitName = "";
  int _type = 1;
  /// 货物类别
  var _categoryname="";
  List<int> _skuResults = [];
  /// spu的每项内容
  dynamic _jSkuOptions1;
  String shopName ="";
  String shopPhone ="";
  int shopId = 0;
  String fhAddress = "";
  String shAddress = "";
  String fhLat = "";
  String shLat = "";
  String fhLng = "";
  String shLng = "";
  String fhStionName = "";
  String shStionName = "";
  String fhStionId = "";
  String shStionId = "";
  String fhAlisName = "";
  String shAlisName = "";
  int fhAlisId = 0;
  int shAlisId = 0;
  String skuOption = "";
  String skuOption3 = "";
  int pickStationId = 0;
  int deliveryStationId = 0;
  int car_load = 1;
  int qty = 0;
  // int weight = 0;
  int skuProductId = 0;
  String skuProductName = "";
  String skuCode = "";
  String spuProductName = "";
  int spuProductId = 0;
  /// 选择中sku_option，包含name,code,val
  var skuOption1 = [];
  int _missionNum = 1;

  @override
  void initState() {
    super.initState();
    shopName = widget.data["merchant_name"];
    _fhNameTextController.text= widget.data["pick_username"];
    _fhPhoneTextController.text= widget.data["pick_tel"];
    _fhCarNoTextController.text= widget.data["pick_car_plate"];
    _shNameTextController.text= widget.data["delivery_username"];
    _shPhoneTextController.text= widget.data["delivery_tel"];
    _shCarNoTextController.text= widget.data["delivery_car_plate"];
    skuProductName = widget.data["spu_product_name"];
    fhAddress = widget.data["pick_address"];
    shAddress = widget.data["delivery_address"];
    fhStionId = widget.data["pick_station_id"];
    fhStionName = widget.data["pick_station_name"];
    shStionId = widget.data["delivery_station_id"];
    shStionName = widget.data["delivery_station_name"];
    fhLat = widget.data["pick_lat"];
    fhLng = widget.data["pick_lng"];
    shLat = widget.data["delivery_lat"];
    shLng = widget.data["delivery_lng"];
    shAlisName = widget.data["delivery_station_alias_name"];
    shAlisId = widget.data["delivery_station_alias_id"];
    fhAlisName = widget.data["pick_station_alias_name"];
    fhAlisId = widget.data["pick_station_alias_id"];
    qty = widget.data["qty"];
    _missionNum = widget.data["mission_num"];
    // weight = widget.data["total_weight"];
    _weightLayoutController.decimal = true;
    _categoryname = widget.data["spu_product_name"] == "" ?  "按件计费": widget.data["spu_product_name"];
    _unit = widget.data["unit"];

    _eventFn = eventBus.on<ClickAddressEvent>().listen((event) {
      setState(() {
        fhStionId = _type == 1? event.stationId : fhStionId ;
        fhStionName = _type == 1? event.stationName : fhStionName ;
        fhLat = _type == 1? event.lat : fhLat ;
        fhLng = _type == 1? event.lng : fhLng ;
        shLat = _type == 2? event.lat : shLat ;
        shLng = _type == 2? event.lng : shLng ;
        shStionName =_type == 2? event.stationName : shStionName;
        shStionId = _type == 2? event.stationId : shStionId ;
        String fhStationName = event.aliasName!=""?"(" + event.stationName + ")":event.stationName;
        fhAddress = _type == 1? event.aliasName + fhStationName : fhAddress;
        String shStationName = event.aliasName!=""?"(" + event.stationName + ")":event.stationName;
        shAddress = _type == 2? event.aliasName + shStationName : shAddress;
        fhAlisName = _type == 1? event.aliasName : fhAlisName;
        fhAlisId = _type == 1? event.aliasId : fhAlisId;
        shAlisName = _type == 2? event.aliasName : shAlisName;
        shAlisId = _type == 2? event.aliasId : shAlisId;
      });
    });
    _eventFn1 = eventBus.on<ClickShopEvent>().listen((event) {
      setState(() {
        shopName = event.name;
        shopPhone = event.phone;
        shopId = event.id;
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventFn.cancel();
    _eventFn1.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: UIColor.color_main,
        appBar: UTitleLayout.getBackTitle(context, "新增运单"),
        body: GestureDetector(
          child: StateLayout(
            url: "/waybill/sku",
            childBuilder: _renderContent,
            dataCallback: _onDataCallback,
          ).padding(EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right)),
          onTap: () {
            Alib.hideKeyboard(context);
          },
        )
    );
  }

  _onDataCallback(dynamic data) {
    _data = data;
    skuProductId = _data[0]["sku_product_id"];
    // skuProductName = _data[0]["sku_product_name"];
    // spuProductName = _data[0]["name"];
    spuProductId = _data[0]["id"];
    // skuOption1 = _data[0]["option1"];
    // skuOption = _data[0]["option1"];
    // skuCode = widget.data["sku_code"];
    skuCode = widget.data["sku_code"] == ""?_getSkuCode() :  widget.data["sku_code"];
    _skuResults =_parseSkuCode(skuCode);
    // _jSkuOptions1 = widget.data["unit"] == ""?jsonDecode(_data[_categoryIndex]["option1"]):jsonDecode(_data[widget.data["unit"]-1]["option1"]);
    // skuOption1 = widget.data["sku_option"];
    // _categoryIndex = widget.data["unit"] -1;
     _getCategoryIndex();
     _setSkuOptions1();
     _getSkuOption1();
    //_reShowSku();
    // _reShowMission();
  }

  _getCategoryIndex() {
    print(widget.data);
    print(_data);
    for(var i =0;i<_data.length;i++) {
      if(_data[i]["id"] == widget.data["spu_product_id"]) {
        _categoryIndex = i;
      }
    }

  }

  _getSkuOption1() {
    List<Object> skuOption1Results = [];
    var _options1 = jsonDecode( _data[_categoryIndex]["option1"]);
    for(var i = 0;i<_skuResults.length;i++){
      // for(var j = 0;j<_options1.length;j++){
        print(_skuResults);
        if(_skuResults[i] !=0){
          skuOption1Results.add({
            "name":_options1[i]["name"].toString(),
            "code":_options1[i]["code"].toString(),
            "val":_options1[i]["val"][_skuResults[i]-1].toString()
          });
        // }
      }
    }
    skuOption1 = skuOption1Results;
    for (var i = 0; i < skuOption1.length; i++) {
      for (var j = i + 1; j < skuOption1.length; j++) {
        if (skuOption1[i]["name"] == skuOption1[j]["name"]) {
          skuOption1.removeAt(j);
          // skuOption1.splice(j, 1);
          j--;
        };
      };
    };
  }

  /// 根据选择的项和数量来获取对应的sku
  _getSkuCode() {
      List arr  = jsonDecode(_data[_categoryIndex]["option3"])["values"];
      List array  = jsonDecode(_data[_categoryIndex]["option1"]);
      for(var i = 0;i < arr.length; i++) {
        int _account = 0;
        for(var z in arr[i].values){
          for(var j = 0;j<_skuResults.length;j++){
            if(z == array[j]["val"][_skuResults[j]-1]){
              _account+=1;
            }
          }
        }
        // 按件计费
        if(_unit==1 && arr[i]["section"] != null) {
          num _qty = _qtyLayoutController.number;
          bool flag = _qty>=jsonDecode(arr[i]["section"])[0] && _qty<=jsonDecode(arr[i]["section"])[1];
          if(_account == _skuResults.length && flag) {
            skuCode = arr[i]["SKU"];
          }
        } else{
          if(_account == _skuResults.length) {
            skuCode = arr[i]["SKU"];
          }
        }
      }
  }

  /// 获取选中结果下标
  _getSpuResult() {
    // 先初始化，避免脏数据
    _skuResults = [];
    List arr  = jsonDecode(_data[_categoryIndex]["option1"]);
    // 根据option1的长度确定
    for(var i = 0 ;i<arr.length;i++){
      // 默认是第一个
      _skuResults.add(1);
    }
  }

  /// 切换获取类别的时候，更新下spu每一项
  _setSkuOptions1() {
    _jSkuOptions1 = jsonDecode(_data[_categoryIndex]["option1"]);
  }

  _reShowMission() {
    var jSkuOptions3 = jsonDecode(_data[_categoryIndex]["option3"]);
    var valuesList = jSkuOptions3["values"];
    valuesList.asMap().keys.map((index) {
      var SKU = valuesList[index]["SKU"];
      if(SKU == skuCode) {
        num car_load = valuesList[index]["car_load"];
        num  qty = _qtyLayoutController.number ?? widget.data['qty'];
        num result = qty / car_load;
        _missionNum = result.ceil();
        setState(() {
          _missionNum = _missionNum;
          _taskLayoutController.number = _missionNum;

        });
        eventBus.fire(ClickAmountEvent(_missionNum));
      }
    }).toList();
  }

  List<int> _parseSkuCode(String code) {

    var begin = -1;
    var end = -1;
    List<int> skuResults = [];
    for (int i = 0; i < code.length; i++) {
      var ch = code.codeUnitAt(i);
      if (_isLetter(ch)) {
        if (begin > 0) {
          end = i;
          skuResults.add(int.parse(code.substring(begin, end)));
          begin = -1;
        }
      } else if (_isDigit(ch)) {
        if (begin == -1) {
          begin = i;
        }
      }
    }
    if (begin > 0) {
      skuResults.add(int.parse(code.substring(begin, code.length)));
    }
    skuResults.removeAt(skuResults.length-1);
    return skuResults;
  }

  bool _isLetter(int code) {
    return code >= "a".codeUnitAt(0) && code <= "z".codeUnitAt(0);
  }

  bool _isDigit(int code) {
    return code >= "0".codeUnitAt(0) && code <= "9".codeUnitAt(0);
  }

  Widget _renderContent(dynamic data) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                //_renderNo(),
                Container(
                    height: 1.rpx,
                    color: UIColor.color_divider),
                _renderShop(),
                10.hspace,
                _deliverInfo(),
                10.hspace,
                _consigneeInfo(),
                10.hspace,
                _renderSKU(),
                10.hspace,
                _renderTask(),
                10.hspace,
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.all(12.rpx),
          child: UText.getBkButton(
            "提交",
            16.rpx,
            bkColor: UIColor.color_primary,
            radius: 12.rpx,
            width: double.infinity,
            height: 48.rpx,
            onPressed: _onClickSubmit,
          ),
        ),
        SizedBox(height: MediaQuery.of(context).padding.bottom),
      ],
    );
  }

  Widget _renderShop() {
    return Container(
      height: 48.rpx,
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Row( children: [
        SizedBox(
            width: 80.rpx,
            child: UText.get("店铺名称", UIColor.color_t5, 16.rpx)
        ),
        Expanded(child:
        GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              OpenUtils.pop2(context, PopShopsList());

            },
            child: Row(
                children: [
                  UText.get(shopName == ""?"请选择店铺名称":shopName, shopName == ""?UIColor.color_t5:UIColor.color_t1, 16.rpx),
                  const Spacer(),
                  Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
                ]
            )
        )
        )
      ],
      ),
    );
  }

  Widget _deliverInfo() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("发货人", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _fhNameTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        decoration: const InputDecoration(
                          hintText: "请输入发货人",
                          border:InputBorder.none,
                          hintStyle: TextStyle(fontSize: 17),
                        )
                    ),
                  ),
                ]
            ),
          ),
          Container(
              height: 1.rpx,
              color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("发货电话", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _fhPhoneTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                        ],
                        maxLength: 11,
                        decoration: const InputDecoration(
                          counterText: "",
                          hintText: "请输入发货电话",
                          border:InputBorder.none,
                          hintStyle: TextStyle(fontSize: 17),
                        )
                    ),
                  ),
                ]
            ),
          ),
          Container(height: 1.rpx,color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
              children: [
                SizedBox(
                    width: 80.rpx,
                    child: UText.get("发货地址", UIColor.color_t5, 16.rpx)
                ),
                Expanded(
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          _type = 1;
                          OpenUtils.open(context,   AddressPage(1,"",0));
                        },
                        child: Row(
                            children: [
                              LimitedBox(
                                maxWidth: 240.rpx,
                                child:
                                Text(fhAddress == ""?"请选择发货地址":fhAddress, style: TextStyle(color:fhAddress == ""?UIColor.color_t5:UIColor.color_t1,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),
                              ),
                              const Spacer(),
                              Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
                            ]
                        )
                    )
                ),
              ],
            ),
          ),
          Container(
              height: 1.rpx,
              color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("发货车牌", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _fhCarNoTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        decoration: const InputDecoration(
                          hintText: "请输入车牌",
                          border:InputBorder.none,
                          hintStyle: TextStyle(fontSize: 17),
                        )
                    ),
                  ),
                ]
            ),
          ),
        ],
      ),
    );
  }

  Widget _consigneeInfo() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("收货人", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _shNameTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        decoration: const InputDecoration(
                          hintText: "请输入收货人",
                          border:InputBorder.none,
                          hintStyle: TextStyle(fontSize: 17),
                        )
                    ),
                  ),
                ]
            ),
          ),
          Container(
              height: 1.rpx,
              color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("收货电话", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _shPhoneTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        inputFormatters: [
                          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                        ],
                        maxLength: 11,
                        decoration: const InputDecoration(
                          counterText: "",
                          hintText: "请输入收货电话",
                          border:InputBorder.none,
                          hintStyle: TextStyle(fontSize: 17),
                        )
                    ),
                  ),
                ]
            ),
          ),
          Container(height: 1.rpx,color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
              children: [
                SizedBox(
                    width: 80.rpx,
                    child: UText.get("收货地址", UIColor.color_t5, 16.rpx)
                ),
                Expanded(
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          _type = 2;
                          OpenUtils.open(context,   AddressPage(1,"",0));
                        },
                        child: Row(
                            children: [
                              LimitedBox(
                                maxWidth: 240.rpx,
                                child: Text(shAddress == ""?"请选择收货地址":shAddress, style: TextStyle(color:shAddress == ""?UIColor.color_t5:UIColor.color_t1,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),
                              ),
                              const Spacer(),
                              Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
                            ]
                        )
                    )
                )
              ],
            ),
          ),
          Container(
              height: 1.rpx,
              color: UIColor.color_divider),
          SizedBox(
            height: 48.rpx,
            child:Row(
                children: [
                  SizedBox(
                      width: 80.rpx,
                      child: UText.get("收货车牌", UIColor.color_t5, 16.rpx)
                  ),
                  Expanded(
                    child: TextField(
                        style: TextStyle(color: UIColor.color_t1, fontSize: 16.rpx),
                        controller: _shCarNoTextController,
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        decoration: const InputDecoration(
                          hintText: "请输入车牌",
                          hintStyle: TextStyle(fontSize: 17),
                          //hintStyle: TextStyle(color: Colors.black.withOpacity(0.26), fontSize: 16.rpx),
                          border:InputBorder.none,
                        )
                    ),
                  ),
                ]
            ),
          ),
        ],
      ),
    );
  }

  Widget _renderSKU() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderSpuType(),
          ..._jSkuOptions1.asMap().keys.map((index) {
            return _renderOneSku(index);
          }).toList(),
          _renderTotalWeight(),
          Container(
              margin: EdgeInsets.only(left: 16.rpx, top: 10.rpx, right: 16.rpx),
              height: 1.rpx,
              color: UIColor.color_divider),
          10.hspace,
          _renderQty(),
          6.hspace,
        ],
      ),
    );
  }

  Widget _renderSpuType() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.get("货物类别", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            16.wspace,
            UText.get(_categoryname, UIColor.color_t1, 14.rpx),
            const Spacer(),
            Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        // 选择货物类别
        OpenUtils.pop(context, PopPickSpu(list: _data, nameKey: "name", initItem: _categoryIndex, callback: (index) {
          setState(() {
            _categoryIndex = index;
            _spuKeyIndex = 0;
            _spuValIndex = 0;
            _categoryname = _data[_categoryIndex]["name"];
            _unit = _data[_categoryIndex]["unit"];
            _unitName = _data[_categoryIndex]["unit_name"];
            skuProductId = _data[_categoryIndex]["sku_product_id"];
            skuProductName = _data[_categoryIndex]["sku_product_name"];
            spuProductName = _data[_categoryIndex]["name"];
            spuProductId = _data[_categoryIndex]["id"];
            var len = jsonDecode(_data[_categoryIndex]["option1"]).length;
            if(len == 1) {
              _skuResults = [1,0];
            } else if(len == 2){
              _skuResults = [1,1,0];
            } else if(len == 3) {
              _skuResults = [1,1,1,0];
            }
            _getSpuResult();
            // _reShowSku();
            // getSkuOption1();
            _getSkuOption1();
            _reShowMission();
            _setSkuOptions1();
            _getSkuCode();
          });
        },));
      },
    );
  }

  Widget _renderOneSku(int index) {
    var sku = _jSkuOptions1[index];
    var list = sku["val"] as List;
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(
          margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          height: 1.rpx,
          color: UIColor.color_divider),
      16.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: UText.get(sku["name"], UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
      ),
      12.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Wrap(
          spacing: 10.rpx,
          runSpacing: 0.rpx,
          children:
          list.asMap().keys.map((valIndex) => _renderOneSkuVal(sku, index, valIndex)).toList(),
        ),
      ),
      16.hspace,
    ]);
  }

  Widget _renderOneSkuVal(dynamic sku, int index, int valIndex) {
    var isSelect = valIndex == _skuResults[index] - 1;
    return UText.getBkButton(
      sku["val"][valIndex],
      14.rpx,
      color: isSelect ? Colors.white : UIColor.color_t3,
      width: 50.rpx,
      height: 32.rpx,
      radius: 8.rpx,
      bkColor: isSelect ? UIColor.color_primary : UIColor.color_input,
      padding: EdgeInsets.symmetric(horizontal: 12.rpx),
      onPressed: () {
        setState(() {
          _spuKeyIndex = index;
          _spuValIndex = valIndex;
        });
        _skuResults[_spuKeyIndex] = _spuValIndex + 1;
        // _reShowSku();
        _getSkuOption1();
        _reShowMission();
        _setSkuOptions1();
        _getSkuCode();
      },
    );
  }

  Widget _renderTotalWeight() {
    Widget rw;
    if( _unit == 1 || _unit == 0 ) {
      rw = 0.wspace;
    } else {
      rw = Container(
          padding:EdgeInsets.fromLTRB(0,10.rpx,0,0),
          margin: EdgeInsets.fromLTRB(16.rpx,0,16.rpx,0),
          decoration: const BoxDecoration(
            border: Border(
                top: BorderSide(width: 1.0, color: UIColor.color_divider)
            ),
          ),
          child: Row(
            children: [
              UText.get("数量（吨）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
              const Spacer(),
              NumberLayout(
                  controller: _weightLayoutController,
                  initNumber: widget.data['qty'],
                  max: 10000,
                  editParentText: () => {

                  }
              ),
            ],
          )
      );
    }
    return rw;
  }

  Widget _renderQty() {
    return Row(
      children: [
        16.wspace,
        UText.get("件数（件）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
        const Spacer(),
        NumberLayout(
            controller: _qtyLayoutController,
            initNumber: qty,
            max: 10000,
            editParentText: () => {
              _reShowMission(),
              _getSkuCode()
            }
        ),
        16.wspace,
      ],
    );
  }

  Widget _renderTask() {
    return Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child:Row(
          children: [
            UText.get("任务数量", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            const Spacer(),
            TaskLayout(
                controller: _taskLayoutController,
                initNumber: _missionNum,
                max: 100,
                editParentText: () => {

                }
            ),
          ],
        )
    );
  }

  _onClickSubmit() {
    if (_fhNameTextController.text == "") {
      Tip.show("请输入发货人");
      return ;
    }
    if (_fhPhoneTextController.text == "") {
      Tip.show("请输入发货电话");
      return ;
    }
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (!exp.hasMatch(_fhPhoneTextController.text)) {
      Tip.show("请输入正确格式的发货电话");
      return ;
    }
    // if ( shAddress== "") {
    //   Tip.show("请选择发货地址");
    //   return ;
    // }
    if (_shNameTextController.text == "") {
      Tip.show("请输入收货人");
      return ;
    }
    if (_shPhoneTextController.text == "") {
      Tip.show("请输入收货电话");
      return ;
    }
    if (!exp.hasMatch(_shPhoneTextController.text)) {
      Tip.show("请输入正确格式的收货电话");
      return ;
    }
    if ( shAddress== "") {
      Tip.show("请选择收货地址");
      return ;
    }
    if (_weightLayoutController.number == 0 && _unit == 2) {
      Tip.show("请输入数量");
      return ;
    }
    if (_qtyLayoutController.number == 0) {
      Tip.show("请输入件数");
      return ;
    }
    if(_taskLayoutController.number == 0){
      Tip.show("请输入任务数量");
      return ;
    }
    for (int i = 0; i < _skuResults.length - 1; i++) {
      if (_skuResults[i] == -1) {
        var tip = "请选择" + _jSkuOptions1[i]["name"];
        Tip.show(tip);
        return ;
      }
    }

    CustomAlertDialog.show(context, title:"确定提交吗?",content: "确认后将对运单进行分配车辆。",confirmText:"确认提交", onConfirm: () {
      var dialog = LoadingDialog(context);
      dialog.show(text: "提交中...");
      //_uploadHelper.upload(success: () {
      var json = _getPostJson();
      Log.i(json);

      var url = "/waybill/create";
      Api.submitx(context, url, data: json, progress: false, success: (data) {
        dialog.hide();
        OpenUtils.open(context, ConfirmOrderSuccessPage(2,widget.data["waybill_no"]));
      }, failTip: "提交失败", fail: (_) {
        dialog.hide();
      });
      // }, fail: () {
      //   dialog.hide();
      //   Tip.show("图片上传失败");
      // });
    });
  }

  dynamic _getPostJson() {
    var json = {};
    json["parent_waybill_no"] = widget.data["waybill_no"];

    json["merchant_id"] = shopId == 0?widget.data["merchant_id"] : shopId;
    json["merchant_name"] = shopName == ""?widget.data["merchant_name"]:shopName;
    json["merchant_phone"] = shopPhone == ""?widget.data["merchant_phone"]: shopPhone;

    json["pick_lng"] = fhLng == widget.data["pick_lng"]? widget.data["pick_lng"] : fhLat;
    json["pick_lat"] = fhLat == widget.data["pick_lat"]? widget.data["pick_lat"] : fhLng;
    json["pick_station_id"] = fhStionId == widget.data["pick_station_id"]?widget.data["pick_station_id"]:fhStionId;
    json["pick_station_name"] = fhStionName == widget.data["pick_station_name"]?widget.data["pick_station_name"]:fhStionName;
    json["pick_username"] = _fhNameTextController.text  == "" ? widget.data["pick_username"] : _fhNameTextController.text;
    json["pick_tel"] = _fhPhoneTextController.text == "" ? widget.data["pick_tel"] : _fhPhoneTextController.text;
    json["pick_address"] = fhAddress == ""?widget.data["pick_address"]:fhAddress;
    json["pick_car_plate"] = _fhCarNoTextController.text == ""? widget.data["pick_car_plate"] : _fhCarNoTextController.text;
    json["pick_station_alias_id"] =fhAlisId == widget.data["pick_station_alias_id"]? widget.data["pick_station_alias_id"]: fhAlisId ;
    json["pick_station_alias_name"] = fhAlisName ==widget.data["pick_station_alias_name"]? widget.data["pick_station_alias_name"] : fhAlisName;

    json["delivery_lng"] = shLng == widget.data["delivery_lng"] ? widget.data["delivery_lng"]:shLng;
    json["delivery_lat"] = shLat == widget.data["delivery_lat"] ? widget.data["delivery_lat"]:shLat;
    json["delivery_station_id"] = shStionId == widget.data["delivery_station_id"]?  widget.data["delivery_station_id"]: shStionId;
    json["delivery_station_name"] = shStionName == widget.data["delivery_station_name"]? widget.data["delivery_station_name"]: shStionName;
    json["delivery_username"] = _shNameTextController.text == "" ?  widget.data["delivery_username"]: _shNameTextController.text;
    json["delivery_tel"] = _shPhoneTextController.text  == ""? widget.data["delivery_tel"]: _shPhoneTextController.text ;
    json["delivery_address"] = shAddress == ""?  widget.data["delivery_address"]: shAddress;
    json["delivery_car_plate"] = _shCarNoTextController.text == "" ?  widget.data["delivery_car_plate"]:  _shCarNoTextController.text;
    json["delivery_station_alias_id"] =shAlisId == widget.data["delivery_station_alias_id"]? widget.data["delivery_station_alias_id"]: shAlisId;
    json["delivery_station_alias_name"] =shAlisName ==widget.data["delivery_station_alias_name"]? widget.data["delivery_station_alias_name"] : shAlisName;

    json["spu_product_id"] = spuProductId == 0?widget.data["spu_product_id"] : spuProductId;
    json["sku_code"] = skuCode ==""?widget.data["sku_code"]:skuCode;
    json["sku_product_id"] = skuProductId == 0?widget.data["sku_product_id"] : skuProductId;
    json["sku_product_name"] = skuProductName == "" ?widget.data["sku_product_name"] : skuProductName;
    json["spu_product_name"] = spuProductName == ""?widget.data["spu_product_name"] : spuProductName;
    json["sku_option"] = skuOption1.length == 0?widget.data["sku_option"] : jsonEncode(skuOption1);//
    json["mission_num"] = _taskLayoutController.number;
    json["unit"] = _unit<1 ? widget.data["unit"]: _unit ;
    json["unit_name"] = _unitName == ""? widget.data["unit_name"] : _unitName;

    var weight = _weightLayoutController.number;
    var qty = _qtyLayoutController.number;
    if(_unit == 2) {
      json["weight"] = (weight * 1000).toInt();
    }
    json["qty"] = qty.toInt();
    return json;
  }
}